﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Orange.Logistics.Models;
using System.Data.SqlClient;

namespace Orange.Logistics.Services {

    public interface IGroupService : IBaseService<Group> {
        IQueryable<Group> GetGroups();
        IQueryable<Customer> GetMemebers(int groupid);
        IQueryable<Customer> GetNoMemebers(int groupid);
        void AddMember(CustomerGroup gc);
        void DeleteMemebers(int groupid, List<Customer> models);
    }

    public class GroupService : BaseService<Group>, IGroupService {


        public IQueryable<Group> GetGroups() {
            return db.Groups;
        }


        public IQueryable<Customer> GetMemebers(int groupid) {
            var query = from c in db.Customers
                        from gc in db.CustomerGroups
                        where gc.Groupid == groupid && gc.Customerid == c.CustomerId
                        orderby gc.CreateTime descending
                        select c;
            return query;
        }


        public IQueryable<Customer> GetNoMemebers(int groupid) {
            var query = from c in db.Customers
                        where !(from gc in db.CustomerGroups
                                where gc.Groupid == groupid
                                select gc.Customerid).Contains(c.CustomerId)
                        select c;
            return query;
        }


        public void AddMember(CustomerGroup gc) {
            db.CustomerGroups.Add(gc);
        }

        public void DeleteMemebers(int groupid, List<Customer> membs) {
            if (membs == null) {
                foreach (var item in db.CustomerGroups.Where(gc => gc.Groupid == groupid)) {
                    db.CustomerGroups.Remove(item);
                }
            } else {
                foreach (var customerId in membs.Select(c => c.CustomerId)) {
                    db.Entry(db.CustomerGroups.Find(groupid, customerId)).State = EntityState.Deleted;
                }
            }
        }
    }
}